<template>
  <view class="user-form-container">
    <form @submit.prevent="handleSubmit" class="user-form">
      <div class="form-group">
        <label for="avatar">头像<span class="required">*</span>:</label>
        <up-upload
          :fileList="fileList1"
          @afterRead="handleAvatarAfterRead"
          @delete="deletePic"
          name="avatar"
          multiple
          :maxCount="1"
        ></up-upload>
        <span v-if="errors.avatar" class="error-message">{{
          errors.avatar
        }}</span>
      </div>

      <div class="form-group">
        <label for="gender">性别<span class="required">*</span>:</label>
        <up-radio-group
          v-model="radiovalue1"
          placement="row"
          @change="groupChange"
        >
          <up-radio
            :customStyle="{ marginBottom: '8px' }"
            v-for="(item, index) in radiolist1"
            :key="index"
            :label="item.name"
            :name="item.name"
            @change="radioChange"
            style="color: white"
          >
          </up-radio>
        </up-radio-group>
        <span v-if="errors.gender" class="error-message">{{
          errors.gender
        }}</span>
      </div>

      <div class="form-group">
        <label for="position">职位<span class="required">*</span>:</label>
        <up-picker
          v-model="formData.position"
          :show="show"
          :columns="columns"
          keyName="label"
          @confirm="onConfirm"
          @cancel="onCancel"
        ></up-picker>
        <up-button @click="show = true">{{ position }}</up-button>
        <span v-if="errors.position" class="error-message">{{
          errors.position
        }}</span>
      </div>

      <div class="form-group">
        <label for="name">姓名<span class="required">*</span>:</label>
        <input
          type="text"
          id="name"
          v-model="formData.name"
          @blur="validateField('name')"
          :class="{ 'input-error': errors.name }"
          placeholder="请输入姓名"
        />
        <span v-if="errors.name" class="error-message">{{ errors.name }}</span>
      </div>

      <div class="form-group">
        <label for="age">年龄<span class="required">*</span>:</label>
        <input
          type="number"
          id="age"
          v-model.number="formData.age"
          @blur="validateField('age')"
          :class="{ 'input-error': errors.age }"
          placeholder="请输入年龄"
          min="0"
        />
        <span v-if="errors.age" class="error-message">{{ errors.age }}</span>
      </div>

      <div class="form-group">
        <label for="contact">联系方式<span class="required">*</span>:</label>
        <input
          type="tel"
          id="contact"
          v-model="formData.contact"
          @blur="validateField('contact')"
          :class="{ 'input-error': errors.contact }"
          placeholder="请输入联系方式"
        />
        <span v-if="errors.contact" class="error-message">{{
          errors.contact
        }}</span>
      </div>

      <div class="form-group">
        <label for="honors"
          >荣誉照片（最多上传五个）<span class="required">*</span>:</label
        >
        <up-upload
          :fileList="ImageList"
          @afterRead="afterReadImage"
          @delete="deleteImage"
          name="honors"
          multiple
          :maxCount="5"
          width="63px"
          height="63px"
        ></up-upload>
        <span v-if="errors.image" class="error-message">{{
          errors.image
        }}</span>
      </div>

      <div class="form-group">
        <label for="resume">简历<span class="required">*</span>:</label>
        <textarea
          id="resume"
          v-model="formData.resume"
          @blur="validateField('resume')"
          :class="{ 'input-error': errors.resume }"
          placeholder="请输入简历"
          rows="4"
        ></textarea>
        <span v-if="errors.resume" class="error-message">{{
          errors.resume
        }}</span>
      </div>

      <button type="submit" class="submit-button" @click="handleSubmit()">
        提交
      </button>
    </form>

    <ksp-cropper
      v-if="showCropper"
      :mode="mode"
      :width="160"
      :height="160"
      :maxWidth="160"
      :maxHeight="160"
      :url="cropperUrl"
      @cancel="oncancelCropper"
      @ok="onokCropper"
    ></ksp-cropper>
  </view>
</template>

<script setup>
import { ref, reactive, defineEmits, onMounted } from "vue";
import kspCropper from "../../../components/ksp-cropper/ksp-cropper.vue";
import instance from "../../../utils/http";

const emit = defineEmits(["submit"]);

const formData = reactive({
  name: "",
  age: null,
  contact: "",
  avatar: "",
  resume: "",
  gender: "男",
  position: "",
  image: [],
});

const errors = reactive({
  name: "",
  age: "",
  contact: "",
  avatar: "",
  resume: "",
  gender: "",
  position: "",
  image: "",
});

const show = ref(false);
const columns = ref([]);
const position = ref("选择所属职位");

const showCropper = ref(false);
const cropperUrl = ref("");
const mode = ref("fixed");

const radiolist1 = reactive([
  { name: "男", disabled: false },
  { name: "女", disabled: false },
]);
const radiovalue1 = ref("男");

const fileList1 = ref([]);
const ImageList = ref([]);

const getPosition = async () => {
  try {
    const response = await instance.get(
      "https://zcgjcy.com/api/getPosition"
    );
    const list = response.data.data.map((item) => ({
      label: item.jobTitle,
      id: item._id,
    }));
    columns.value = [list];
  } catch (err) {
    console.error("获取职位列表失败:", err);
  }
};

onMounted(() => {
  getPosition();
});

const onConfirm = (value) => {
  formData.position = value.value[0].id;
  position.value = value.value[0].label;
  show.value = false;
};

const onCancel = () => {
  show.value = false;
};

const groupChange = (n) => {
  console.log("groupChange", n);
};

const radioChange = (n) => {
  console.log("radioChange", n);
  formData.gender = n;
};

const deletePic = (event) => {
  fileList1.value.splice(event.index, 1);
  formData.avatar = "";
};

const deleteImage = (event) => {
  ImageList.value.splice(event.index, 1);
  updateImageList();
};

const deletePics = () => {
  fileList1.value = [];
  ImageList.value = [];
  formData.avatar = "";
  formData.image = [];
};

const handleAvatarAfterRead = async (event) => {
  const file = event.file[0];
  if (!file) return;

  cropperUrl.value = file.url;
  showCropper.value = true;
};

const oncancelCropper = () => {
  showCropper.value = false;
  cropperUrl.value = "";
};

const onokCropper = async (ev) => {
  const croppedPath = ev.path;
  showCropper.value = false;
  cropperUrl.value = "";

  try {
    const uploadedUrl = await uploadFilePromise(croppedPath, "avatar");
    formData.avatar = uploadedUrl;
    fileList1.value = [
      {
        url: uploadedUrl,
        status: "success",
      },
    ];
  } catch (error) {
    errors.avatar = error;
    formData.avatar = "";
    fileList1.value = [];
  }
};

const afterReadImage = async (event) => {
  const files = event.file;
  for (const file of files) {
    try {
      const uploadedUrl = await uploadFilePromise(file.url, "image");
      ImageList.value.push({
        url: uploadedUrl,
        status: "success",
      });
      formData.image.push(uploadedUrl);
    } catch (error) {
      errors.image = error;
    }
  }
};

const uploadFilePromise = (filePath, type) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: "https://zcgjcy.com/api/upload",
      filePath: filePath,
      name: "file",
      formData: {
        user: "test",
      },
      success: (res) => {
        if (!res.data) {
          reject("返回数据为空");
          if (type === "avatar") {
            errors.avatar = "上传头像失败，请重试";
          } else {
            errors.image = "上传荣誉照片失败，请重试";
          }
          return;
        }
        let parsedData;
        try {
          parsedData = JSON.parse(res.data);
        } catch (error) {
          if (type === "avatar") {
            errors.avatar = "上传数据解析失败";
          } else {
            errors.image = "上传数据解析失败";
          }
          reject("解析失败");
          return;
        }
        if (parsedData.code !== 200) {
          if (type === "avatar") {
            errors.avatar = `上传失败: ${parsedData.msg}`;
          } else {
            errors.image = `上传失败: ${parsedData.msg}`;
          }
          reject(`上传失败: ${parsedData.msg}`);
          return;
        }
        if (parsedData.path) {
          const fileUrl = `https://zcgjcy.com/api/${parsedData.path}`;
          resolve(fileUrl);
        } else {
          if (type === "avatar") {
            errors.avatar = "返回数据格式不正确";
          } else {
            errors.image = "返回数据格式不正确";
          }
          reject("返回数据格式错误");
        }
      },
      fail: (error) => {
        if (type === "avatar") {
          errors.avatar = "上传请求失败";
        } else {
          errors.image = "上传请求失败";
        }
        reject(`上传请求失败: ${error.errMsg}`);
      },
    });
  });
};

const validateField = (field) => {
  switch (field) {
    case "name":
      errors.name = formData.name.trim() === "" ? "姓名不能为空" : "";
      break;
    case "age":
      if (formData.age == null || formData.age === "") {
        errors.age = "年龄不能为空";
      } else if (formData.age < 0 || formData.age > 120) {
        errors.age = "请输入有效的年龄";
      } else {
        errors.age = "";
      }
      break;
    case "contact":
      const contactPattern = /^1[3-9]\d{9}$/;
      errors.contact =
        formData.contact.trim() === ""
          ? "联系方式不能为空"
          : !contactPattern.test(formData.contact)
          ? "请输入有效的手机号码"
          : "";
      break;
    case "avatar":
      errors.avatar = formData.avatar === "" ? "请上传头像" : "";
      break;
    case "resume":
      errors.resume = formData.resume.trim() === "" ? "简历不能为空" : "";
      break;
    case "gender":
      errors.gender = formData.gender === "" ? "请选择性别" : "";
      break;
    case "position":
      errors.position = formData.position.trim() === "" ? "请选择职位" : "";
      break;
    default:
      break;
  }
};

const validateForm = () => {
  validateField("name");
  validateField("age");
  validateField("contact");
  validateField("avatar");
  validateField("resume");
  validateField("position");
  return !Object.values(errors).some((error) => error !== "");
};

const handleSubmit = () => {
  if (validateForm()) {
    console.log("表单提交成功", formData);
    emit("submit", { ...formData });
    resetForm();
  } else {
    console.log("表单验证失败", errors);
  }
};

const resetForm = () => {
  deletePics();
  formData.name = "";
  formData.age = null;
  formData.contact = "";
  formData.avatar = "";
  formData.resume = "";
  formData.position = "";
  formData.image = [];
  Object.keys(errors).forEach((key) => (errors[key] = ""));
};

const updateImageList = () => {
  formData.image = ImageList.value.map((item) => item.url);
};
</script>

<style scoped>
.user-form {
  width: 100%;
  max-width: 500px;
  background: rgb(51, 47, 56);
  border-radius: 8px;
  padding: 20px;
  box-sizing: border-box;
}

.form-group {
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
}

label {
  margin-bottom: 5px;
  font-weight: bold;
  color: white;
}

.required {
  color: red;
}

input,
textarea {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  color: white;
  background: transparent;
}

input::placeholder,
textarea::placeholder {
  color: rgb(255, 255, 255);
}

.input-error {
  border-color: red;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
  font-weight: bold;
}

.submit-button {
  width: 100%;
  padding: 10px 15px;
  background-color: rgb(237, 110, 67);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-button:hover {
  background-color: rgb(247, 164, 136);
}

ksp-cropper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
}
</style>
